import { setWatcher } from '../../utils/watch';
import { requestPromise } from '../../utils/request'

Page({
	data: {
		curNo: 1,    //当前题目序号
		tempQId: null,
		tempAnswer: null,
		myAnswers: [],
		isCorrected: [],
		touchStart: [],
		touchEnd: [],
		isFirst: true,
		isLast: false,
		questions: [],
		questionsNum: 0,
		fieldId: 0
	},

	radioChange(e) {
		const curQId = e.currentTarget.dataset.qid;
		const curAnswer = e.detail.value;
		this.setData({
			tempQId: curQId,
			tempAnswer: curAnswer
		});
	},

	inputChange(e) {
		const curQId = e.currentTarget.dataset.qid;
		const curAnswerPartIdx = e.currentTarget.dataset.idx;
		const curAnswer = e.detail.value;
		let tempAnswer = this.data.tempAnswer;
		if (!tempAnswer || !Array.isArray(tempAnswer)) {
			tempAnswer = [];
		}
		tempAnswer[curAnswerPartIdx] = curAnswer;
		this.setData({
			tempQId: curQId,
			tempAnswer: tempAnswer
		});
	},

	checkboxChange(e) {
		const curQId = e.currentTarget.dataset.qid;
		let curAnswer = e.detail.value;
		curAnswer = curAnswer.sort((a, b) => { return a - b })
		this.setData({
			tempQId: curQId,
			tempAnswer: curAnswer
		});
	},

	bindTextAreaBlur(e) {
		const curQId = e.currentTarget.dataset.qid;
		const curAnswer = e.detail.value;
		this.setData({
			tempQId: curQId,
			tempAnswer: curAnswer
		});
	},

	// 手指触摸动作开始
	onTouchstart(e) {
		let x = e.touches[0].pageX;
		let y = e.touches[0].pageY;
		this.data.touchStart = [x, y];
	},

	// 手指触摸后移动
	onTouchmove(e) {
		let x = e.touches[0].pageX;
		let y = e.touches[0].pageY;
		this.data.touchEnd = [x, y];
	},

	// 手指触摸动作结束
	onTouchcend(e) {
		let start = this.data.touchStart;
		let end = this.data.touchEnd;
		// 切换下一题
		if (start[0] - end[0] > 160) {
			if (this.data.curNo >= 0 && this.data.curNo < this.data.questions.length) {
				this.setData({
					curNo: this.data.curNo + 1,
					//scrollLeft: this.data.curNo * 320
				});
			} else {
				wx.showModal({
					title: "提示",
					content: "已经是最后一题了~"
				})
			}
		} else {
			this.setData({
				//scrollLeft: (this.data.curNo-1) * 320
			});
		};
		// 切换上一题
		if (end[0] - start[0] > 160) {
			if (this.data.curNo == 0) {
				wx.showModal({
					title: "提示",
					content: "已经是第一题了~"
				})
			} else {
				this.setData({
					curNo: this.data.curNo - 1,
					//scrollLeft: (this.data.curNo-2) * 320
				});
			}
		} else {
			this.setData({
				//scrollLeft: (this.data.curNo-1) * 320
			});
		}
	},

	goPre(e) {
		const { curNo, myAnswers } = this.data;
		if (this.data.isFirst) {
			wx.showModal({
				title: "提示",
				content: "已经是第一题了~"
			})
		} else if (myAnswers[curNo - 2]) {
			this.setData({
				curNo: this.data.curNo - 1
			});
		} else if (!myAnswers[curNo - 1]) {
			const curQId = this.data.tempQId;
			const curAnswer = this.data.tempAnswer;
			if (!curAnswer) {
				wx.showModal({
					title: "提示",
					content: "请先完成本道题目~"
				})
			}
			curQId && curAnswer && this.submitMyAnswer(curQId, curAnswer);
			this.setData({
				curNo: this.data.curNo - 1
			});
		} else {
			this.setData({
				curNo: this.data.curNo - 1
			});
		}
	},

	goNext(e) {
		const { curNo, myAnswers, tempAnswer } = this.data;
		if (this.data.isLast && tempAnswer) {
			this.onSubmit();
		} else if (this.data.isLast) {
			wx.showModal({
				title: "提示",
				content: "已经是最后一题了~"
			})
		} else if (!myAnswers[curNo - 1]) {
			const curQId = this.data.tempQId;
			const curAnswer = this.data.tempAnswer;
			if (!curAnswer) {
				wx.showModal({
					title: "提示",
					content: "请先完成本道题目~"
				})
				return;
			}
			curQId && curAnswer && this.submitMyAnswer(curQId, curAnswer);
			this.setData({
				curNo: this.data.curNo + 1
			});
		} else {
			this.setData({
				curNo: this.data.curNo + 1
			});
		}

	},

	skip(e) {
		const idx = e.currentTarget.dataset.idx;
		const { curNo, myAnswers } = this.data;
		if (myAnswers[idx]) {
			this.setData({
				curNo: idx + 1,
				//scrollLeft: idx * 320
			});
		} else if (!myAnswers[idx] && myAnswers[idx - 1]) {
			this.setData({
				curNo: idx + 1
			});
		} else if (!myAnswers[curNo - 1]) {
			wx.showModal({
				title: "提示",
				content: "请先完成本道题目~"
			})
		} else if (!myAnswers[idx] && !myAnswers[idx - 1]) {
			wx.showModal({
				title: "提示",
				content: "请先完成前面的题目~"
			})
		}
	},

	submitMyAnswer(id, ans) {
		const answerArr = this.data.myAnswers;
		const curidx = this.data.curNo - 1;
		answerArr[curidx] = ans;
		this.checkAnswer(curidx, ans);
		this.setData({
			tempQId: null,
			tempAnswer: null,
			myAnswers: answerArr,
		})
		console.log("finishChanged,myAnswers:", this.data.myAnswers);
	},

	checkAnswer(idx, ans) {
		const { isCorrected, questions } = this.data;
		const rightAns = questions[idx].answer;
		isCorrected[idx] = ans.toString() == rightAns.toString() ? 't' : 'f';
		this.setData({
			isCorrected: isCorrected
		})
	},

	getScore() {
		const isCorrected = this.data.isCorrected;
		let score = 0;
		for (const res of isCorrected) {
			res === 't' && score++;
		};
		return score;
	},

	onSubmit(e) {
		const len = this.data.questions.length;
		const { myAnswers, tempAnswer, tempQId, curNo, questions, isCorrected } = this.data;
		if (myAnswers.length < len - 1) {
			wx.showModal({
				title: "提示",
				content: "请先完成所有题目~"
			})
			return;
		}
		if (!tempAnswer) {
			wx.showModal({
				title: "提示",
				content: "请先完成本道题目~"
			})
			return;
		} else {
			const _this = this;
			wx.showModal({
				title: "提示",
				content: "是否确认交卷？",
				success(res) {
					if (res.confirm) {
						_this.submitMyAnswer(questions[len - 1].qid, tempAnswer);
						console.log('确认提交 查看成绩');
						const answerSheet = _this.createAnswerSheet();
						const score = _this.getScore();
						console.log(_this.data.fieldId, answerSheet);
						console.log("score:", score);
						wx.request({
							url: 'http://localhost:8000/scores',
							method: 'POST',
							data: {
								fieldId: _this.data.fieldId,
								record: answerSheet,
								score: score
							},
							success: res => {
								console.log(res);
							},
						})
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		}
	},

	createAnswerSheet() {
		const { myAnswers, questions } = this.data;
		const sheet = questions.map((item, index) => {
			return { qid: item.qid }
		});
		sheet.forEach((item, index) => {
			return item["answer"] = myAnswers[index]
		});
		return sheet;
	},

	bindscrolltoupper(e) {
		wx.showModal({
			title: "提示",
			content: "已经是第一题了~"
		})
	},

	bindscrolltolower(e) {
		wx.showModal({
			title: "提示",
			content: "已经是最后一题了~"
		})
	},

	watch: {
		curNo(val) {
			if (val === this.data.questions.length) {
				this.setData({
					isLast: true
				})
			} else {
				this.setData({
					isLast: false
				})
			}
			if (val === 1) {
				this.setData({
					isFirst: true
				})
			} else {
				this.setData({
					isFirst: false
				})
			}
		}
	},

	getQuestions(fid, num) {
		console.log("获取问卷题目", fid, num);
		wx.request({
			url: `http://localhost:8000/questions?fieldId=${fid}&questionsNum=${num}`,
			success: res => {
				console.log(res.data);
				this.setData({
					questions: res.data
				})
			},
		})
	},

	getQuestionById(qid) {
		return new Promise((resolve,reject) => {
			wx.request({
				url: `http://localhost:8000/questions`,
				method: 'POST',
				data: {
					id: qid
				},
				success: res => {
					this.setData({
						questions: res.data
					});
					resolve("finish getQuestions");
				},
			})
		})
	},

	initRecordData(record) {
		const myAnswers = [];
		const qid = [];
		record.forEach((item, index) => {
			myAnswers[index] = item.answer;
			qid[index] = item.qid;
		});
		this.setData({
			myAnswers: myAnswers,
			questionsNum: record.length,
		});
		this.getQuestionById(qid)
			.then(res=>{
				myAnswers.forEach((ans, idx) => {
					this.checkAnswer(idx, ans);
				})
			})
			.then(() =>{
				console.log(this.data);
			})
	},

	getRecord(id) {
		requestPromise(`http://localhost:8000/scores/${id}`)
			.then(res => {
				const record = res.data[0].record;
				this.initRecordData(record)
			})
	},

	onLoad(options) {
		setWatcher(this);
		const { questionsNum, fieldId, sheetId } = options;
		if (!sheetId) {
			this.setData({
				isCorrected: new Array(this.data.questions.length).fill(''),
				questionsNum: questionsNum,
				fieldId: fieldId
			})
			this.getQuestions(fieldId, questionsNum);
		} else {
			console.log("show Detail");
			this.getRecord(sheetId);
		}
	},
})


